package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.github.savvasdalkitsis.jtmdb.Movie;
import com.movieknight.MovieCheck;

/**
 * Our main activity, show a list of MovieChecks and allows to select some of them
 * 
 * @author marvinlabs
 */
public class MoviesDeleteActivity extends ListActivity {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	private List<Movie> displayMovies;
	private SQLMoviesDataSource datasource;
	List<SQLMovie> values = new ArrayList<SQLMovie>();
	
	private List<MovieCheck> data;
	private ListView listView;
	private MoviesDeleteListAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		datasource = new SQLMoviesDataSource(this);
		datasource.open();
        
		if(values!=null)
			values.clear();
		Socket server = ((MovieKnightApp) this.getApplication()).getServer();
		String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
		int tempError = -1;
				
		PrintWriter out = null;
		try {
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);	
			out.println("{\"module\": \"movies\", \"method\": \"get_movies\",\"session_id\": \"" + sessionID + "\"}");
					
			BufferedReader input = null;
			String st = null;
			input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
			st = input.readLine();//Get Response from Server		
			JSONObject jsonObject = null;
			JSONArray jsonArray = null;
				
			//Parse response
			try {
				jsonObject = new JSONObject(st);
				jsonArray = jsonObject.getJSONArray("movies");
			
				//Error Code
				tempError = Integer.parseInt(jsonObject.getString("error_code"));
				
			//END SERVER ------------------------------------------------------
			
			if(tempError ==0)
			{	
				for(int i = 0; i < jsonArray.length(); i++){
					List<Movie> tempList = Movie.imdbLookup(jsonArray.getString(i));
					if(tempList.size()>0)
					{
						Movie temp = tempList.get(0);
						SQLMovie tempSQLMovie = new SQLMovie((long)i, temp.getID());
						
						values.add(tempSQLMovie);
						Log.v("movie", jsonArray.getString(i));
					}
				}
				
				//Convert SQLMovies ints into TMDBMovies
        		//values = datasource.getAllMovies();
                displayMovies = new ArrayList<Movie>();
                for(int i = 0; i < values.size(); i++) {
        			try {
        		        Movie temp = Movie.getInfo(values.get(i).getMovie());
        				displayMovies.add(temp);
        			} catch (IOException e) {
        				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + 27205, e);
        			} catch (JSONException e) {
        				Log.w(LOG_TAG, "JASONException while fetching movie ID" + 27205, e);
        			}
                }
   			
			}
			
			} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		setContentView(R.layout.movie_delete);
		
        /*//Convert SQLMovies ints into TMDBMovies
        displayMovies = new ArrayList<Movie>();
        for(int i = 0; i < values.size(); i++) {
			try {
		        Movie temp = Movie.getInfo(values.get(i).getMovie());
				displayMovies.add(temp);
			} catch (IOException e) {
				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + 27205, e);
			} catch (JSONException e) {
				Log.w(LOG_TAG, "JASONException while fetching movie ID" + 27205, e);
			}
        }*/

		// Create some sample data and sort it alphabetically
		// --
		data = new ArrayList<MovieCheck>();
		for(int i = 0; i < displayMovies.size(); i++) {
			data.add(new MovieCheck(displayMovies.get(i).getID(), displayMovies.get(i).getName()));
		}

		// Create the adapter to render our data
		// --
		adapter = new MoviesDeleteListAdapter(this, data);
		setListAdapter(adapter);

		// Get some views for later use
		// --
		listView = getListView();
		listView.setItemsCanFocus(false);
		
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}

	/**
	 * Called when the user presses one of the buttons in the main view
	 */
	public void onButtonClick(View v) {
		switch (v.getId()) {
		case R.id.removeMoviesButton:
			returnSelectedMovieCheckIds();
			break;
		case R.id.cancelButton:
			setResult(RESULT_OK);
			finish();
			break;
		}
	}

	/**
	 * Show a message giving the selected MovieCheck IDs. There seems to be a bug with
	 * ListView#getCheckMovieCheckIds() on Android 1.6 at least @see
	 * http://code.google.com/p/android/issues/detail?id=6609
	 */
	private void returnSelectedMovieCheckIds() {
		// Get an array that contains the IDs of the list MovieChecks that are checked
		// --
		
		final long[] checkedMovieCheckIds = listView.getCheckItemIds();
		if (checkedMovieCheckIds == null) {
			Toast.makeText(this, "No selection", Toast.LENGTH_LONG).show();
			return;
		}

		// For each ID in the status array
		// --
		final int checkedMovieChecksCount = checkedMovieCheckIds.length;
		for (int i = 0; i < checkedMovieChecksCount; ++i) {
			
			Long templong = checkedMovieCheckIds[i];
			int tempint = templong.intValue();

			SQLMovie temp = new SQLMovie(templong,tempint);
			//temp.setId(templong);
			//temp.setMovie(tempint);
			
			// SERVER: Delete movie with TMDB ID: templong.
			Movie tempMovie = null;
			try {
				tempMovie = Movie.getInfo(tempint);
				
				String imdb = tempMovie.getImdbID();
				Socket server = ((MovieKnightApp) this.getApplication()).getServer();
				String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
				int tempError = -1;
				
				PrintWriter out = null;
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
				out.println("{\"module\": \"movies\", \"method\": \"del_movie\",\"session_id\": \"" + sessionID + "\", \"params\": {\"movie_id\": \"" + imdb + "\"}}");
				
				BufferedReader input;
				String st = null;
		        input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
				st = input.readLine();//Get Response from Server		
				JSONObject jsonObject = null;	
				
				//Parse response
				try {
					jsonObject = new JSONObject(st);
				
			
				//Error Code
				tempError = Integer.parseInt(jsonObject.getString("error_code"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//END SERVER ------------------------------------------------------
			
			if(tempError==0){
				datasource.deleteMovie(temp);
				Log.w(LOG_TAG, "Removed movie" + templong);
			}
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		datasource.close();
		setResult(RESULT_OK);
		finish();
	}
}